package com.ruoyi.framework.config;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.ruoyi.common.SecurityUtils;
import java.time.LocalDateTime;
import java.util.Arrays;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Desc: MybatisPlus配置类
 * @Author LuoYong
 * @Date 2022/1/12 11:15
 */
@Configuration
@MapperScan("com.ruoyi.project.**.mapper")
public class MybatisPlusConfig {

    /**
     * 分页插件
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        // count计数
        mybatisPlusInterceptor.setInterceptors(
                Arrays.asList(new PaginationInnerInterceptor(), new OptimisticLockerInnerInterceptor()));
        return mybatisPlusInterceptor;
    }


    /**
     * 自动填充
     */
    @Bean
    public MetaObjectHandler metaObjectHandler() {
        return new MetaObjectHandler() {
            @Override
            public void insertFill(MetaObject metaObject) {
                String userName = "未知";
                // if (ObjectUtil.isNotNull(SecurityUtils.getUsername())) {
                //     userName = SecurityUtils.getUsername();
                // }
                this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
                this.strictInsertFill(metaObject, "version", Integer.class, 1);
                this.strictInsertFill(metaObject, "delFlag", Integer.class, 0);
                this.strictInsertFill(metaObject, "createBy", String.class, userName);
            }

            @Override
            public void updateFill(MetaObject metaObject) {
                String userName = "未知";
                // if (ObjectUtil.isNotNull(SecurityUtils.getUsername())) {
                //     userName = SecurityUtils.getUsername();
                // }
                this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
                this.setFieldValByName("updateBy", userName, metaObject);
            }
        };
    }
}